package com.Trie.lsj;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class FileUtil {
	 static int maxLen = 1;
	/**
	 * 读取词典文件，获取词典中最大词的长度
	 * @param dicPath
	 * @return
	 */
		public static List<String> readDic(String dicPath){
		    System.out.println("读取词典文件......");
			BufferedReader br  = null;
			try {
				File file = new File(dicPath);
				FileReader fr = new FileReader(file);
				br = new BufferedReader(fr);
				List<String> list = new ArrayList<String>();
				String str;
				while ((str = br.readLine()) != null) {
					list.add(str);
					if((str.trim()).length() > maxLen){
		                maxLen = (str.trim()).length();
		            }
				}
				 System.out.println("词典读取成功.");
		         System.out.println("最大分词长度为："+ maxLen);
				return list;
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					br.close();
				} catch (IOException e) {
					System.err.println("Error! 词典装载失败!");
					e.printStackTrace();
				}
			}
		return null;
	}
		/**
		 * 输出分词结果的txt文件
		 * @param result
		 */
		public static void writer(String result){
			BufferedWriter bw = null;
			try {
				File file = new File("Result.txt");
				FileWriter fw = new FileWriter(file,true);
				bw = new BufferedWriter(fw);
				bw.write(result);
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					bw.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		/**
		 * 读取待分词的txt文件
		 * @param result
		 * @param filePath
		 * @return
		 */
		public static String readFile(String filePath){
			BufferedReader br  = null;
			try {
				File file = new File(filePath);
				FileReader fr = new FileReader(file);
				br = new BufferedReader(fr);
				char[] c = new char[(int)file.length()];
				String str = null;
				
				while ((br.read(c)) != -1) {
					str = String.valueOf(c);
				}
				return str.trim();
			} catch (IOException e) {
				e.printStackTrace();
			}finally{
				try {
					br.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		return null;
	}

	}
